// pages/home/home.js
import Service from "../../model/service"
const service = new Service();
import Category from "../../model/category"
import { throttle } from "../../utils/utils"


Page({

    /**
     * 页面的初始数据
     */
    data: {
        tabs: ['全部服务', '在提供', '正在找'],

        categoryList: [],

        serviceList: [],

        tabIndex: 0,

        categoryId: 0,

        loading: true
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: async function (options) {
        await this._getServiceList();
        await this._getCategoryList();
        this.setData({ loading: false })
    },

    async _getServiceList() {
        const serviceList = await service.reset().getServiceList(this.data.categoryId, this.data.tabIndex)
        // console.log(serviceList);
        this.setData({
            serviceList: serviceList
        })
    },

    handleTabChange(e) {
        this.data.tabIndex = e.detail.index
        this._getServiceList();
    },

    handleCategoryChange: throttle(function (e) {
        if (this.data.categoryId === e.currentTarget.dataset.id) {
            return
        }
        this.data.categoryId = e.currentTarget.dataset.id
        this._getServiceList();
    }),


    async _getCategoryList() {
        const categoryList = await Category.getCategoryListWithAll()
        this.setData({
            categoryList: categoryList
        })
    },

    async onPullDownRefresh() {
        this._getServiceList();
        wx.stopPullDownRefresh();
    },

    async onReachBottom() {
        if (!service.hasMoreData) {
            return
        }
        const serviceList = await service.getServiceList(this.data.categoryId, this.data.tabIndex)
        this.setData({
            serviceList: serviceList
        })
    },


    handleSelectService: function (event) {
        const service = event.currentTarget.dataset.service
        wx.navigateTo({
            url: "/pages/service-detail/service-detail?service_id=" + service.id
        })
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})